package com.feige.utils;


import com.feige.constant.Constants;
import com.feige.entity.SecurityUser;
import com.feige.utils.redis.RedisUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class TokenUtils {
    @Resource
    private RedisUtils redisUtils;


    /**
     * 验证token过期时间，小于20分中则刷新缓存
     * @param securityUser
     */
    public void verifyToken(SecurityUser securityUser){
        Long expireTime = securityUser.getExpireTime();
        Long currentTime = System.currentTimeMillis();
        if (currentTime - expireTime < Constants.TWENTY_MINUTE){
            saveSecurityUserCache(securityUser);
        }
    }

    /**
     * 保存用户到缓存
     * @param securityUser
     */
    public void saveSecurityUserCache(SecurityUser securityUser){
        securityUser.setUuid(securityUser.getCurrentUser().getNum());
        securityUser.setLoginTime(System.currentTimeMillis());
        securityUser.setExpireTime(System.currentTimeMillis() + Constants.Key_EXPIRE);
        String key = Constants.LOGIN_USER_KEY + securityUser.getCurrentUser().getNum() + securityUser.getCurrentUser().getUsername();
        redisUtils.set(key, securityUser,Constants.Key_EXPIRE);
    }
}
